package amazons3utils

import (
	"bytes"
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"io"
	"log"
	"mime/multipart"
	"sync"
)

var(
	acess_key  = "admin"
	secret_key  = "admin123"
	endpoint  = "http://192.168.232.135:9000"
	disableSSL = true
	region = "us-east-1"

)

func SetParams(ak,sk,url string)  {
	acess_key = ak
	secret_key = sk
	endpoint = url
}
var  mysesson *session.Session
var once sync.Once


func GetSession() *session.Session  {
	once.Do(func() {
		mysesson,_=NewSession(acess_key,secret_key,endpoint)
	})
	return mysesson
}



//创建 session
func NewSession(ak,sk,url string) (*session.Session, error){
	creds := credentials.NewStaticCredentials(ak, sk, "")
	config := &aws.Config{
		Region:           aws.String(region),
		Endpoint:         &url,
		S3ForcePathStyle: aws.Bool(true),
		Credentials:      creds,
		DisableSSL:       &disableSSL,
	}
	return session.NewSession(config)
}

//创建 bucket

func CreateBucket(bucket  string,sess *session.Session) bool  {


	svc := s3.New(sess)

	params := &s3.CreateBucketInput{
		Bucket: aws.String(bucket),
	}
	_, err := svc.CreateBucket(params)

	if err != nil {
		fmt.Println(err)
		return false
	} else {
		return true
	}
}

//列出所有 bucket
func ListBucket(sess *session.Session)  {

	svc := s3.New(sess)

	_,_ = svc.ListBuckets(&s3.ListBucketsInput{})
}
//列出一个 bucket 的所有 object
func ListBucketObject(bucket string,sess *session.Session)  {

	svc := s3.New(sess)

	params := &s3.ListObjectsInput{
		Bucket:             aws.String(bucket), // Required
	}
	_, _ = svc.ListObjects(params)
}

func PutObject(bucket ,k string,v []byte,sess *session.Session) bool  {

	svc := s3.New(sess)

	params := &s3.PutObjectInput{
		Bucket:             aws.String(bucket), // Required
		Key:                aws.String(k),  // Required
		//Body:               strings.NewReader(value),
		Body:               bytes.NewReader(v),
	}
	_, err := svc.PutObject(params)
	if err != nil {
		return false
	}else{
		return true
	}
}

//上传文件
func UploadingFile(bucket string,filename string,file *multipart.FileHeader,sess *session.Session) bool {
	src, err := file.Open()
	if err != nil {
		return false
	}
	defer src.Close()
	uploader := s3manager.NewUploader(sess)
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(filename),
		Body:   src,
		//Metadata:map[string]*string{"Content-Type":file.},
		ContentType:&file.Header["Content-Type"][0],
	})

	if err != nil {
		log.Print(err)
		return false
	} else {
		return true
	}
}

type FakeWriterAt struct {
	w io.Writer
}
func (fw FakeWriterAt)WriteAt(p []byte, off int64) (n int, err error){

	//忽略'offset'，因为我们强制顺序下载
	return fw.w.Write(p)

}

//下载文件
func DownloadFile(bucket string,filename string,w io.Writer,sess *session.Session) (int64,error)  {

	wa := FakeWriterAt{
		w:w,
	}
	downloader := s3manager.NewDownloader(sess)
	numBytes, err := downloader.Download(wa,
		&s3.GetObjectInput{
			Bucket: aws.String(bucket),
			Key:    aws.String(filename),
		})
	return numBytes,err
}
